package com.shensi.adminCollect.service.station.impl;



import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.shensi.adminCollect.domain.system.HttpRequestUtil;
import com.shensi.adminCollect.domain.system.QrCodeRes;
import com.shensi.adminCollect.domain.system.Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * <Title>工具类: WeiXinUtil</Title>
 * <description> 获取微信用户信息和凭证 </description>
 * @author JK
 * @date 2019年11月10日
 */
public class WeiXinUserUtil {

    //微信小程序获取用户信息 https://api.weixin.qq.com/sns/userinfo
    //public final static String weiXinUserInfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
    //凭证获取路径
    public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    //微信小程序路径获取openID "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=APPSECRET&js_code=CODE&grant_type=authorization_code";
    public final static String OPENID_URL  ="https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=APPSECRET&js_code=CODE&grant_type=authorization_code";

    //微信公众号获取通过code换取网页授权access_token
    public final static String GZHAUTHORIZEINFO_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    //获取UnionId
    public final static String unionId_Url ="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    //获取公众号jsapi_ticket
    private static final String JSAPI_TICKET_URL ="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";

    //获取公众号微信卡api_ticket ticket/getticket
    private static final String CARD_API_TICKET_URL ="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card";

    //获取公众号模板列表
    private static final String ALL_PRIVATE_TEMPLATE_URL ="https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=ACCESS_TOKEN";

    // 获取生成带参数的二维码ticket
    private static final String WX_QR_CODE = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s";
    // 获取生成带参数的二维码
    private static final String WX_QR_CODE_URL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s";

    //日志
    private static final Logger logger = LoggerFactory.getLogger(WeiXinUserUtil.class);


    /*
     * 获取公众号微信卡券api_ticket
     * @param accessToken
     * @return
     */
    public static JSONObject getGzhCardApiTicket(String accessToken){
        String requestUrl =CARD_API_TICKET_URL.replace("ACCESS_TOKEN",accessToken);
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("获取公众号微信卡券api_ticket：" + jsonObject.toString());
        return jsonObject;

    }

    /*
     * 获取公众号jsapi_ticket
     * @param accessToken
     * @return
     */
    public static JSONObject getGzhJsapiTicket(String accessToken){
        String requestUrl =JSAPI_TICKET_URL.replace("ACCESS_TOKEN",accessToken);
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("获取公众号jsapi_ticket：" + jsonObject.toString());
        return jsonObject;

    }


    /*
     * 获取用户公众号的授权信息
     * @param appId
     * @param appSecret
     * @param code
     * @return
     */
    public static JSONObject getGzhAuthorizeInfo(String appId, String appSecret, String code){
        logger.info("appId参数: "+ appId+" ;appSecret参数: " +appSecret +" ;code参数: " +code);
        String requestUrl = GZHAUTHORIZEINFO_URL.replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code);
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("获取用户公众号的授权后信息：" + jsonObject.toString());
        return jsonObject;
    }


    /*
     * 获取公众号UnionId信息
     * @param accessToken
     * @param openId
     * @return
     */
    public static JSONObject getUnionIdInfo(String accessToken, String openId){
        String requestUrl = unionId_Url.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("获取UnionId信息：" + jsonObject.toString());
        return jsonObject;
    }

    /*
     * 获取用户的openid和session_key 格式例子:{"session_key":"rlxKT/xhq2bxAuvrMeEq8Q==","openid":"o9RM50ppeCgx065T2PvJjtzB_Gmo"}
     * @param appId     //凭证
     * @param appSecret     //密钥
     * @param code
     * @return
     */
    public static Map<String, Object> getUserSessionKeyAndOpenID(String appId, String appSecret, String code){
        String requestUrl = OPENID_URL.replace("APPID", appId).replace("APPSECRET", appSecret).replace("CODE", code);
        Map<String, Object> resultMap = new HashMap<>();
        //发起GET请求
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("用户通过code获取到信息：:" + jsonObject.toString());
        if(jsonObject != null && jsonObject.containsKey("openid")){
            resultMap.put("openId", jsonObject.getString("openid"));
        }
        if(jsonObject != null && jsonObject.containsKey("session_key")){
            resultMap.put("sessionKey", jsonObject.getString("session_key"));
        }
        if(jsonObject != null && jsonObject.containsKey("unionid")){
            resultMap.put("unionId", jsonObject.getString("unionid"));
        }
        resultMap.put("code", code);
        return resultMap;
    }

    /*
     * 获取公众号模板列表
     * @param accessToken
     * @return
     */
    public static JSONObject getAllPrivateTemplate(String accessToken){
        String requestUrl =ALL_PRIVATE_TEMPLATE_URL.replace("ACCESS_TOKEN",accessToken);
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("获取公众号模板列表：" + jsonObject.toString());
        return jsonObject;

    }

    /*
     * 获取接口访问凭证
     * @param appId         //凭证
     * @param appSecret     //密钥
     * @return
     */
    public static Token getToken(String appId, String appSecret){
        Token token = null;
        String requestUrl = token_url.replace("APPID", appId).replace("APPSECRET", appSecret);
        //发起GET请求获取凭证
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        System.out.println("getToken: "+jsonObject);
        if(jsonObject != null){
            try {
                token = new Token();
                token.setAccessToken(jsonObject.getString("access_token"));
                token.setExpiresIn(jsonObject.getInteger("expires_in"));
            }catch (JSONException e){
                e.printStackTrace();
            }
        }
        return token;
    }

    /*
     * 从redis获取token
     * @param appId
     * @param appSecret
     * @return
     */
//    public String getTokenByRedisCache(String appId, String appSecret){
//        logger.info("appId参数: "+ appId+" ;appSecret参数: " +appSecret);
//        String tokenCache ="";
//        if(!redisCacheUtil.hasKey(appId)){
//            String token = WeiXinUserUtil.getToken(appId, appSecret).getAccessToken();
//            redisCacheUtil.setCacheObject(appId, token);
//            redisCacheUtil.expire(appId, 7200, TimeUnit.SECONDS);
//            tokenCache = token;
//            logger.info("Redis缓存中token信息: " + tokenCache);
//        }else {
//            tokenCache = redisCacheUtil.getCacheObject(appId);
//        }
//        return tokenCache;
//    }
    /**
     * 获取公众号动态二维码
     *
     * @param token  授权token
     * @param key    场景值（标识）
     * @param type   二维码时效 false 临时 true 永久
     * @param expire 时效
     * @return
     */
    public static QrCodeRes getQrcode(String token, String key, boolean type, Long expire) {
        String url = String.format(WX_QR_CODE, token);
        JSONObject scene = new JSONObject();
        scene.put("scene_str", key);
        JSONObject actionInfo = new JSONObject();
        actionInfo.put("scene", scene);
        JSONObject req = new JSONObject();

        // QR_LIMIT_STR_SCENE(永久)  QR_STR_SCENE （临时）
        if (type) {
            req.put("action_name", "QR_LIMIT_STR_SCENE");
        } else {
            req.put("action_name", "QR_STR_SCENE");
            req.put("expire_seconds", expire);
        }
        req.put("action_info", actionInfo);
        String data = JSONObject.toJSONString(req);
        //发送post请求
        logger.info("weixin getQrcode url : " + url);
        logger.info("weixin getQrcode req : " + JSONObject.toJSONString(data));
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(url, "POST", data);
        logger.info("weixin getQrcode res : " + JSONObject.toJSONString(jsonObject));

        if (null != jsonObject) {
            try {
                QrCodeRes qrCodeRes = new QrCodeRes();
                qrCodeRes.setTicket(jsonObject.getString("ticket"));
                qrCodeRes.setUrl(jsonObject.getString("url"));
                qrCodeRes.setQrCodeUrl(String.format(WX_QR_CODE_URL, URLEncoder.encode(jsonObject.getString("ticket"), "UTF-8")));
                return qrCodeRes;
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage());
            }
        }
        // 二维码：https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQGE8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyam80X3dYRDVkb0gxNjZxaDFBYzYAAgQGIAhkAwSAOgkA
        return null;
    }

}
